package pbl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 
 * @author @author AMPM
 *
 */

public class TcpIMHandler implements Runnable{
	private Socket socket;
	
	public TcpIMHandler(Socket socket) {
		this.socket = socket;
	}
	
	public void run()  {
		while (true) {
		try {
		
			// get the input and output stream from the socket
			InputStream is = socket.getInputStream();
			OutputStream os = socket.getOutputStream();
			
			// wrap them in the ObjectInputStream and ObjectOutputStream objects
			ObjectOutputStream oos = new ObjectOutputStream( os );
			ObjectInputStream ois = new ObjectInputStream(is);
	    
			// get the message sent from the client side
			String message = (String) ois.readObject();
			System.out.println(message);
			
			// get an input from user
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String input = br.readLine().trim();
			
			// the user input is written to the ObjectOutputStream and flushed
			oos.writeObject( input );
			oos.flush();

		}
		catch (IOException ignore) {}
		catch (ClassNotFoundException ignore) {}
	}
	}
}


